<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="退款单号" prop="refundNo">
        <el-input
          v-model="queryParams.refundNo"
          placeholder="请输入退款单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="refundType">
        <el-select v-model="queryParams.refundType" placeholder="请选择退款类型" clearable>
          <el-option
            v-for="dict in dict.type.ec_refund_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="金额" prop="refundAmount">
        <el-input
          v-model="queryParams.refundAmount"
          placeholder="请输入退款金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="refundStatus">
        <el-select v-model="queryParams.refundStatus" placeholder="请选择退款状态" clearable>
          <el-option
            v-for="dict in dict.type.ec_refund_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- 删除按钮已删除 -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['fun:refund:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="refundList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户" align="center" prop="userName" width="120" />
      <el-table-column label="创建组织" align="center" width="120">
        <template slot-scope="scope">
          <span>{{ getDeptName(scope.row.orgId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退款单号" align="center" prop="refundNo" width="180" />
      <el-table-column label="订单号" align="center" prop="orderNo" width="180" />
      <el-table-column label="退款类型" align="center" prop="refundType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ec_refund_type" :value="scope.row.refundType"/>
        </template>
      </el-table-column>
      <el-table-column label="退款原因" align="center" prop="refundReason" />
      <el-table-column label="退款金额" align="center" prop="refundAmount" />
      <el-table-column label="退款状态" align="center" prop="refundStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ec_refund_status" :value="scope.row.refundStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center" prop="applyTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理时间" align="center" prop="handleTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.handleTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户备注" align="center" prop="handleNote" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="handle-note-text">{{ scope.row.handleNote }}</span>
        </template>
      </el-table-column>
      <el-table-column label="凭证图片" align="center" prop="evidenceImages" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.evidenceImages" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <!-- 操作列已隐藏 -->
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['fun:refund:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fun:refund:remove']"
          >删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改退款/售后对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="退款单号" prop="refundNo">
          <el-input v-model="form.refundNo" placeholder="请输入退款单号" />
        </el-form-item>
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="退款类型" prop="refundType">
          <el-select v-model="form.refundType" placeholder="请选择退款类型">
            <el-option
              v-for="dict in dict.type.ec_refund_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="退款原因" prop="refundReason">
          <el-input v-model="form.refundReason" placeholder="请输入退款原因" />
        </el-form-item>
        <el-form-item label="退款金额" prop="refundAmount">
          <el-input v-model="form.refundAmount" placeholder="请输入退款金额" />
        </el-form-item>
        <el-form-item label="退款状态" prop="refundStatus">
          <el-radio-group v-model="form.refundStatus">
            <el-radio
              v-for="dict in dict.type.ec_refund_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="申请时间" prop="applyTime">
          <el-date-picker clearable
            v-model="form.applyTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择申请时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="处理时间" prop="handleTime">
          <el-date-picker clearable
            v-model="form.handleTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择处理时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="处理备注" prop="handleNote">
          <el-input v-model="form.handleNote" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="凭证图片" prop="evidenceImages">
          <image-upload v-model="form.evidenceImages"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRefund, getRefund, delRefund, addRefund, updateRefund } from "@/api/fun/refund"
import { getDept } from "@/api/system/dept"
import ImagePreview from "@/components/ImagePreview"
import ImageUpload from "@/components/ImageUpload"

export default {
  name: "Refund",
  components: {
    ImagePreview,
    ImageUpload
  },
  dicts: ['ec_refund_status', 'ec_refund_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 退款/售后表格数据
      refundList: [],
      // 部门名称缓存
      deptNameCache: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        refundNo: null,
        orderNo: null,
        userId: null,
        refundType: null,
        refundReason: null,
        refundAmount: null,
        refundStatus: null,
        applyTime: null,
        handleTime: null,
        handleNote: null,
        evidenceImages: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        refundNo: [
          { required: true, message: "退款单号不能为空", trigger: "blur" }
        ],
        orderNo: [
          { required: true, message: "订单号不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        refundType: [
          { required: true, message: "退款类型不能为空", trigger: "change" }
        ],
        refundAmount: [
          { required: true, message: "退款金额不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {    /** 根据部门ID获取部门名称 */
    getDeptName(deptId) {
      if (!deptId) return '-'
      if (this.deptNameCache[deptId]) {
        return this.deptNameCache[deptId]
      }
      // 异步获取部门名称
      getDept(deptId).then(response => {
        this.$set(this.deptNameCache, deptId, response.data.deptName)
        // 强制更新视图
        this.$forceUpdate()
      }).catch(() => {
        this.$set(this.deptNameCache, deptId, '未知组织')
        this.$forceUpdate()
      })
      return deptId // 先显示ID，异步加载完成后显示名称
    },
    /** 查询退款/售后列表 */
    getList() {
      this.loading = true
      listRefund(this.queryParams).then(response => {
        this.refundList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 查看退款详情 */
    handleView(row) {
      const refundId = row.refundId
      this.$router.push({ path: '/fun/refund/detail', query: { refundId: refundId } })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        refundId: null,
        refundNo: null,
        orderNo: null,
        userId: null,
        refundType: null,
        refundReason: null,
        refundAmount: null,
        refundStatus: null,
        applyTime: null,
        handleTime: null,
        handleNote: null,
        evidenceImages: null,
        createTime: null,
        updateTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.refundId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加退款/售后"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const refundId = row.refundId || this.ids
      getRefund(refundId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改退款/售后"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.refundId != null) {
            updateRefund(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addRefund(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const refundIds = row.refundId || this.ids
      this.$modal.confirm('是否确认删除退款/售后编号为"' + refundIds + '"的数据项？').then(function() {
        return delRefund(refundIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fun/refund/export', {
        ...this.queryParams
      }, `refund_${new Date().getTime()}.xlsx`)
    },
    /** 获取第一张图片 */
    getFirstImage(images) {
      if (!images) return null
      const imageList = images.split(',')
      return imageList.length > 0 ? imageList[0].trim() : null
    },
    /** 图片加载错误处理 */
    handleImageError() {
      // 图片加载失败时的处理逻辑
    }
  }
}
</script>

<style scoped>
.handle-note-text {
  display: inline-block;
  max-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
